import {
  registerMicroApps,
  start,
  initGlobalState,
  MicroAppStateActions
} from 'qiankun'
import { config } from './microAppConfig'
import { removeToken } from '@/utils/cookies'
import { PermissionModule } from '@/store/modules/permission'
import router from '@/router/index'

registerMicroApps(config)

const actions: MicroAppStateActions = initGlobalState({
  clearCookie: false,
  meta: {}
})
actions.onGlobalStateChange((state, prev) => {
  // state: 变更后的状态; prev 变更前的状态
  // 如果子应用设置state.clearCookie，则调用这个方法
  if (state.clearCookie) {
    removeToken()
    window.location.href = `/login?redirect=${window.location.pathname}`
  }
  // 如果子应用改变了meta信息，对应改变面包屑
  if (state.meta.activeMenu && state.meta.activeMenu !== prev.meta.activeMenu) {
    PermissionModule.GenerateSidebarMenu({
      path: state.meta.activeMenu,
      meta: state.meta
    })
    PermissionModule.SET_BY_MICRO()
    setTimeout(() => {
      PermissionModule.SET_BY_MAIN()
    }, 100)
  } else {
    PermissionModule.SET_BY_MAIN()
  }
})
export { start, config }
